import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'

export interface Props {

}

export interface Refs {

}

const ReadWeight = forwardRef<Refs, Props>((props, ref) => {
  const {} = props
  const [ envCheck, setEnvCheck ] = useState<boolean>(false)
  const [ serialConnect, setSerialConnect ] = useState<boolean>(false)

  useEffect(() => { connectSerial() }, [])

  useImperativeHandle(ref, () => {
    return {

    }
  })
  
  const connectSerial = async () => {
    try {
      const envCheck = 'searial' in navigator
      if (!envCheck) {
        throw new Error('Not supported')
      }

      setEnvCheck(true)

      const port = await navigator.serial.requestPort({
        filters: [{ usbVendorId: 0xabcd }]
      })
      console.log(port)

      setSerialConnect(true)
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '15px' }}>
      <span>环境是否支持: <span style={{ color: envCheck ? 'green' : 'red' }}>{ envCheck ? '支持' : '不支持' }</span></span>
      <span>当前串口连接状态: <span style={{ color: serialConnect ? 'green' : 'red' }}>{ serialConnect ? '已连接' : '未连接' }</span></span>
      <input
        style={{ width:  '60%', height: '30px', borderRadius: '50px', textAlign: 'center' }}
        placeholder='这里读取重量'
      />
    </div>
  )
})

export default ReadWeight
